﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Indigo.Quibbler.Data;
using Indigo.Quibbler.Library;
using System.Diagnostics;


namespace Indigo.Quibbler.Controls
{
    public partial class SpiderControl : UserControl
    {
        #region Private Members
        private NewsArticle _centerArticle = null;
        private string _searchTerm = string.Empty;
        private string _categoryContext = string.Empty;
        private List<NewsArticle> _relatedArticles = null;
        #endregion

        #region Properties
        public NewsArticle CenterArticle
        {
            get { return _centerArticle; }
            set
            {
                _centerArticle = value;
                _LoadItems();
            }
        }

        public string SearchTerm
        {
            get { return _searchTerm; }
            set
            {
                _searchTerm = value;
                _LoadItems();
            }
        }

        public string CategoryContext
        {
            get { return _categoryContext; }
            set
            {
                _categoryContext = value;
                _LoadItems();
            }
        }

        public SpiderMode CurrentMode { get; set; }
        #endregion

        #region Ctor
        public SpiderControl()
        {
            InitializeComponent();
            photoExplorer.CenterNode = new SpiderControlCenterNode(null);

            this.Loaded += new RoutedEventHandler(SpiderControl_Loaded);
        }
        #endregion

        #region Public Event
        public delegate void SpiderArticleClickedEventHandler(object sender, SpiderEventArgs eventArgs);
        public event SpiderArticleClickedEventHandler Click;
        public event EventHandler Closed;
        #endregion

        #region Event Handlers
        private void SpiderControl_Loaded(object sender, RoutedEventArgs e)
        {
            btnClose.Click += new RoutedEventHandler(btnClose_Click);
        }

        void btnClose_Click(object sender, RoutedEventArgs e)
        {
            if (Closed != null)
                Closed(this, new EventArgs());
        }
        private void hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
        {
            string uri = e.Uri.AbsoluteUri;
            Process.Start(new ProcessStartInfo(uri));
            e.Handled = true;
        }
        #endregion

        #region Helper Functions
        private void _LoadItems()
        {
            try
            {
                SearchManager searchManager = new SearchManager();
                string keywords = string.Empty;

                switch (CurrentMode)
                {
                    case SpiderMode.RelatedArticle:
                        if (_centerArticle == null) break;
                        photoExplorer.CenterNode = new SpiderControlCenterNode(_centerArticle);
                        keywords = (_centerArticle.Keywords.Count > 0) ? string.Join(" ", _centerArticle.Keywords.ToArray()) : _centerArticle.Headline;
                        string[] searchResults = searchManager.Search(keywords, string.Empty, SearchManager.SearchType.Keyword, SearchManager.SearchIndexType.News);

                        if (searchResults != null && searchResults.Length > 0)
                        {
                            //Parser parser = new Parser();
                            _relatedArticles = _RemoveCenterNode(Parser.Articles(searchResults, false), _centerArticle);
                            foreach (NewsArticle cur in _relatedArticles)
                            {
                                if (string.IsNullOrEmpty(cur.Id) || cur.Id != _centerArticle.Id)
                                    photoExplorer.CenterNode.RelatedNodes.Add(new SpiderControlBaseNode(cur));
                            }
                        }
                        break;
                    case SpiderMode.Search:
                        photoExplorer.CenterNode = new SpiderControlSearchCenterNode(_searchTerm);
                        searchResults = searchManager.Search(_searchTerm, string.Empty, SearchManager.SearchType.FullText, SearchManager.SearchIndexType.News);

                        if (searchResults != null && searchResults.Length > 0)
                        {
                            //Parser parser = new Parser();
                            try
                            {
                                _relatedArticles = Parser.Articles(searchResults, false);
                            }
                            catch (Exception ex) { Utilities.Log("Error in parsing Search Results", ex); }
                            if (_relatedArticles == null || _relatedArticles.Count == 0)
                            {
                                photoExplorer.CenterNode = new SpiderControlSearchCenterNode("No Search Results",_searchTerm);
                                return;
                            }
                            int i = 0;
                            foreach (NewsArticle cur in _relatedArticles)
                            {
                                i++;
                                photoExplorer.CenterNode.RelatedNodes.Add(new SpiderControlBaseNode(cur));
                                if (i > 8)
                                    break;
                            }
                        }
                        else //No Search Results
                            photoExplorer.CenterNode = new SpiderControlSearchCenterNode("No Search Results",_searchTerm);
                        break;
                    case SpiderMode.PhotoGallery:
                        photoExplorer.CenterNode = new SpiderPhotoNode(_centerArticle);
                        keywords = (_centerArticle.Keywords.Count > 0) ? string.Join(" ", _centerArticle.Keywords.ToArray()) : _centerArticle.Headline;
                        searchResults = searchManager.Search(keywords, string.Empty, SearchManager.SearchType.Keyword, SearchManager.SearchIndexType.PhotoGallery);

                        if (searchResults != null && searchResults.Length > 0)
                        {
                            //Parser parser = new Parser();
                            _relatedArticles = _RemoveCenterNode(Parser.Articles(searchResults, true), _centerArticle);
                            foreach (NewsArticle cur in _relatedArticles)
                            {
                                photoExplorer.CenterNode.RelatedNodes.Add(new SpiderPhotoNode(cur));
                            }
                        }
                        break;
                    case SpiderMode.SearchPhoto:
                        photoExplorer.CenterNode = new SpiderControlSearchCenterNode(_searchTerm);
                        searchResults = searchManager.Search(_searchTerm, string.Empty, SearchManager.SearchType.FullText, SearchManager.SearchIndexType.PhotoGallery);

                        if (searchResults != null && searchResults.Length > 0)
                        {
                            //Parser parser = new Parser();
                            _relatedArticles = Parser.Articles(searchResults, true);
                            int i = 0;
                            foreach (NewsArticle cur in _relatedArticles)
                            {
                                i++;
                                photoExplorer.CenterNode.RelatedNodes.Add(new SpiderPhotoNode(cur));
                                if (i > 8)
                                    break;
                            }
                        }
                        break;
                }
            }
            catch (Exception ex) { Utilities.Log("Search error: ", ex); }
        }

        private List<NewsArticle> _RemoveCenterNode(List<NewsArticle> list, NewsArticle _centerArticle)
        {
            int count = 8;

            List<NewsArticle> result = new List<NewsArticle>();
            try
            {
                foreach (NewsArticle cur in list)
                {
                    if (cur.Headline == _centerArticle.Headline && cur.Id == _centerArticle.Id) continue;
                    if (result.Count >= count)
                        break;
                    result.Add(cur);
                }
            }
            catch { ; }
            return result;
        }

        private void _articleSpider_Click(object sender, MouseButtonEventArgs e)
        {
            switch (CurrentMode)
            {
                case SpiderMode.RelatedArticle:
                    SpiderNode _articleControl = (SpiderNode)sender;
                    if (_articleControl.Article == CenterArticle)
                    {
                        if (Click != null)
                        {
                            Click(sender, new SpiderEventArgs() { SelectedArticle = _articleControl.Article, ItemSource = _GetAllArticles(_relatedArticles) });
                        }
                    }
                    else
                    {
                        _centerArticle = _articleControl.Article;
                        _LoadItems();
                    }
                    break;

                case SpiderMode.Search:
                    _articleControl = (SpiderNode)sender;
                    if (Click != null)
                    {
                        Click(sender, new SpiderEventArgs() { SelectedArticle = _articleControl.Article, ItemSource = _GetAllArticles(_relatedArticles) });
                    }
                    break;

                case SpiderMode.PhotoGallery:
                    SpiderImageControl _spiderImageControl = (SpiderImageControl)sender;
                    if (Click != null)
                    {
                        Click(sender, new SpiderEventArgs() { SelectedArticle = _spiderImageControl.Article, ItemSource = _GetAllArticles(_relatedArticles) });
                    }
                    break;

                case SpiderMode.SearchPhoto:
                    _spiderImageControl = (SpiderImageControl)sender;
                    if (_spiderImageControl.Article == CenterArticle)
                    {
                        if (Click != null)
                        {
                            Click(sender, new SpiderEventArgs() { SelectedArticle = _spiderImageControl.Article, ItemSource = _GetAllArticles(_relatedArticles) });
                        }
                    }
                    else
                    {
                        _centerArticle = _spiderImageControl.Article;
                        _LoadItems();
                    }
                    break;
            }
        }

        private List<NewsArticle> _GetAllArticles(List<NewsArticle> _relatedArticles)
        {
            List<NewsArticle> result = new List<NewsArticle>();
            if (CurrentMode == SpiderMode.PhotoGallery || CurrentMode == SpiderMode.RelatedArticle)
            {

                if (_relatedArticles != null) result = _relatedArticles;
                result.Add(_centerArticle);
            }
            else
            {
                if (_relatedArticles != null) result = _relatedArticles;
            }
            return result;
        }

        private void _spiderDoubleClicked(object sender, MouseButtonEventArgs e)
        {
            switch (CurrentMode)
            {
                case SpiderMode.RelatedArticle:
                    SpiderNode _articleControl = (SpiderNode)sender;
                    if (Click != null)
                    {
                        Click(sender, new SpiderEventArgs() { SelectedArticle = _articleControl.Article, ItemSource = _GetAllArticles(_relatedArticles) });
                    }
                    break;

                case SpiderMode.Search:
                    _articleControl = (SpiderNode)sender;
                    if (Click != null)
                    {
                        Click(sender, new SpiderEventArgs() { SelectedArticle = _articleControl.Article, ItemSource = _GetAllArticles(_relatedArticles) });
                    }
                    break;

                case SpiderMode.PhotoGallery:
                    SpiderImageControl _spiderImageControl = (SpiderImageControl)sender;
                    if (Click != null)
                    {
                        Click(sender, new SpiderEventArgs() { SelectedArticle = _spiderImageControl.Article, ItemSource = _GetAllArticles(_relatedArticles) });
                    }
                    break;

                case SpiderMode.SearchPhoto:
                    _spiderImageControl = (SpiderImageControl)sender;
                    if (Click != null)
                    {
                        Click(sender, new SpiderEventArgs() { SelectedArticle = _spiderImageControl.Article, ItemSource = _GetAllArticles(_relatedArticles) });
                    }

                    break;
            }
        }
        #endregion


    }

    public enum SpiderMode { RelatedArticle, Search, PhotoGallery, SearchPhoto };

    public class SpiderEventArgs
    {
        public NewsArticle SelectedArticle { get; set; }
        public List<NewsArticle> ItemSource { get; set; }
    }
}
